import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

import entity.WebPage;


public class QueueServer {
	
	private static Queue<String> queue;
	private static QueueServer server = null;
	
	private QueueServer() {
		
		queue = new LinkedList();
	}
	
	public static QueueServer getInstance() {
		if(server == null)
			server = new QueueServer();
		
		return server;
	}
	
	
	public synchronized ArrayList getNextUrlBatch() {
		int batchCount = 5;
		ArrayList urlList = new ArrayList();
		
		for(int i = 0; i < batchCount; i++) {
			
			if(queue.peek() != null)
				urlList.add(queue.poll());
				
		}
		
		return urlList;
			
	}
		
	//method to add new url to the queue	
	public boolean addUrl(String address) {
		
		try {
			if(!UrlExists(address)) {
				URL url = new URL(address);
				queue.offer(address);
			}
		
		}
		catch (Exception e){
			return false;
		}
		
		return true;
		
	}
	
	public boolean UrlExists(String url) {
		Iterator <String> iterator = queue.iterator();		
		while(iterator.hasNext()) {
			String compareUrl = iterator.next();
			//if url exists in queue, return true
			if(compareUrl.equalsIgnoreCase(url)) {
				return true;
			}
		}

		//else return false
		return false;
	}
		

}
